<template>
  <Modal class="caggiage-goods-modal" v-model="modal" :title="title" fullscreen>
    <p class="caggiage-top-title"><Icon class="icon" type="ios-alert" />未被划分的收货地区按该模板的计费规则计费，需指定地区计费的可在列表页新建店铺模板设置</p>
    <div class="form-content">
      <Form :model="form" :label-width="100" ref="form" :rules="rules">
        <FormItem label="模板名称" prop="freightName">
          <Input v-model.trim="form.freightName" placeholder="模板名称..."/>
        </FormItem>
        <FormItem label="配送描述" prop="deliveryDescribe">
          <Input v-model.trim="form.deliveryDescribe" :maxlength="100" placeholder="配送描述..." @on-blur="onBlur"/>
        </FormItem>
        <FormItem label="经销商设置" v-if="!isDefault">
          <div><Button @click="onAddDis" type="primary" size="small">为指定经销商设置运费</Button></div>
          <div class="distributor-list">
            <span>{{distributorDTOS | fliterValue}}</span>
          </div>
        </FormItem>
        <FormItem label="计费规则">
          <p class="big">配送</p>
          <RadioGroup v-model="form.freightType" >
            <div class="mb">
              <Radio label="FREIGHT_FREE">每张订单不满<InputNumber class="ml mr" v-model="defaultFee" :min="0" :precision="2"/>元，运费<InputNumber class="ml mr" v-model="extraFee" :min="0" :precision="2"/>元</Radio>
            </div>
            <div>
              <Radio label="FREIGHT">固定运费<InputNumber class="ml mr" v-model="fixedFee" :min="0" :precision="2"/>元</Radio>
            </div>
          </RadioGroup>
        </FormItem> 
      </Form>
    </div>
    <div slot="footer">
      <Button :disabled="disabled" @click="onSave" type="primary" size="large">保存且返回</Button>
      <Button @click="modal = false" size="large" type="text">返回</Button>
    </div>
    <DealerChange ref="dealer-change" :isShop="isShop" :distributorIdsAll="distributorIdsAll" @onComplete="onComplete"/>
</Modal>
</template>
<script>
import DealerChange from './DealerChange'
export default {
  components: {
    DealerChange
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入模板名称'));
      } else {
        this.checkOnly().then(() =>{
          if (this.flag) {
            callback(new Error('模板名称不可重复'));
          } else {
            callback();
          }
        })   
      }
    }
    return {
      isDefault: false,
      isShop: true,
      modal: false,
      id: null,
      freightTemplateId: null,
      title: '',
      disabled: false,
      flag: false,
      rules: {
        freightName: [{required: true, validator: validateName, trigger: "blur"}],
        deliveryDescribe: [{required: true, message: '请输入配送描述', trigger: "blur"}]
      },
      form: {
        freightName: '',
        deliveryDescribe: '',
        freightType: 'FREIGHT_FREE'
      },
      defaultFee: null,
      extraFee: null,
      fixedFee: null,
      distributorDTOS: [],
      distributorIdsAll: []
    }
  },
  methods: {
    updateForm(id, isDefault = false, freightTemplateId = null) {
      this.resetForm()
      this.isDefault = isDefault
      this.id = id
      this.title = this.id ? '修改店铺运费模板' : '创建店铺运费模板'
      if (id) {
        this.freightTemplateId = freightTemplateId
        this.getInfo(id)
      }
      this.modal = true
      this.getAllIds()
    },
    resetForm() {
      this.freightTemplateId = null
      this.form.freightName = ''
      this.form.deliveryDescribe = '',
      this.form.freightType = 'FREIGHT_FREE'
      this.defaultFee = null
      this.extraFee = null
      this.fixedFee = null
      this.distributorDTOS = []
    },
    getInfo(id) {
      let params = {
        id
      }
      this.$ajaxGet('/freight/setting/detail', params).then(data => {
        this.form.freightName = data.freightName
        if (this.isDefault && !this.form.freightName) this.form.freightName = '普通配送'
        this.form.deliveryDescribe = data.freightTemplateItemDTOS[0].deliveryDescribe
        this.form.freightType = data.freightTemplateItemDTOS[0].freightType
        if (this.form.freightType === 'FREIGHT') {
          this.fixedFee = data.freightTemplateItemDTOS[0].fixedFee
          this.defaultFee = null
          this.extraFee = null
        } else {
          this.fixedFee = null
          this.defaultFee = data.freightTemplateItemDTOS[0].defaultFee
          this.extraFee = data.freightTemplateItemDTOS[0].extraFee
        }

        this.distributorDTOS = data.freightTemplateItemDTOS && data.freightTemplateItemDTOS[0].distributorDTOS.map(item => {
          return {
            id: item.distributorId,
            value: item.distributorName
          }
        })
      })
    },
    getAllIds() {
      let params = {
        freightTemplateId: this.freightTemplateId ? this.freightTemplateId : null
      }
      this.$ajaxGet('/freight/setting/shop/distributorIds', params).then(data => {
        this.distributorIdsAll = data
      })
    },
    onComplete(obj) {
      this.distributorDTOS = obj.caggiageDealeredList
    },
    onAddDis() {
      this.$refs['dealer-change'].onOpen(1, 2, this.distributorDTOS)
    },
    onSave() {
      if (this.disabled) return
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          let text = ''
          if (this.form.freightType === 'FREIGHT') {
            if (!this.fixedFee && this.fixedFee !== 0) text = '请填写固定运费'
          } else {
            if ((!this.defaultFee && this.defaultFee !== 0) || (!this.extraFee && this.extraFee !== 0)) text = '请填写计费规则'
          }
          if (text) {
            this.$Notice.warning({
              title: text
            })
            this.disabled = false
            return
          }
          let param = {
            freightName: this.form.freightName,
            freightType: 'SHOP_FREIGHT',
            freightCover: 'BUYER_BEAR', // 写死
            freightRule: 'ITEM', // 写死
            isOpenFree: false, // 写死
            id: this.id
          }
          let freightTemplateItemDTOS = []
          let distributorIds = this.distributorDTOS.map(m => m.id)
          freightTemplateItemDTOS.push({
            distributorIds,
            freightType: this.form.freightType,
            deliveryDescribe: this.form.deliveryDescribe,
            isDefault: false,
            id: this.id
          })
          if (this.form.freightType === 'FREIGHT_FREE') {
            freightTemplateItemDTOS[0].defaultFee = this.defaultFee
            freightTemplateItemDTOS[0].extraFee = this.extraFee
            if (freightTemplateItemDTOS[0].fixedFee) delete freightTemplateItemDTOS[0].fixedFee
          } else {
            freightTemplateItemDTOS[0].fixedFee = this.fixedFee
            if (freightTemplateItemDTOS[0].defaultFee) delete freightTemplateItemDTOS[0].defaultFee
            if (freightTemplateItemDTOS[0].extraFee) delete freightTemplateItemDTOS[0].extraFee
          }
          param.freightTemplateItemDTOS = freightTemplateItemDTOS
          let url = this.id ? '/freight/setting/update' : '/freight/setting/save'
          this.$jsonPost(url, param).then(() => {
            this.disabled = false
            this.$Notice.success({
              title: '操作成功'
            })
            this.$emit('onFinish')
            this.modal = false
          }).catch(() => {
            this.disabled = false
          })
        } else {
          this.disabled = false
        }
      })
    },
    onBlur() {
      let params = {
        describeName: this.form.deliveryDescribe,
        id: this.id
      }
      this.$ajaxPost('/freight/setting/describe/exist', params).then(data => {
        if (!data) return
        this.$Notice.warning({
          title: '配送描述不可重复'
        })
        this.form.deliveryDescribe = ''
      })
    },
    async checkOnly() {
      let param = {
        freightName: this.form.freightName,
        id: this.id
      }
      await this.$ajaxPost('/freight/setting/name/exist', param).then(data => {
        this.flag = data
      })
    }
  },
  filters: {
    fliterValue(arr) {
      let text = ''
      arr.forEach(item => {
        text += item.value + ', '
      })
      text = text.substring(0, text.length - 2)
      return text
    }
  }
}
</script>